package com.link.base.base.shorturl.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.base.shorturl.service.ShortURLService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.link.base.base.shorturl.model.ShortURL;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 短链接-
 *
 * @author 姚润发
 * @date 2019/06/04 15:32
 */
@Controller
@RequestMapping("/link/shortURL")
public class ShortURLController extends BasicController<ShortURL> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private ShortURLService shortURLService;

    @Override
    public BasicService<ShortURL> getBasicService() throws Exception {
        return shortURLService;
    }

    /**
     * 根据短连接编码重定向到原页面
     * @param code
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "r/{code}", method = RequestMethod.GET)
    public void redirect(@PathVariable(value = "code", required = true) String code,
                         HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String redirectURL = shortURLService.getRedirectURL(code);
            if (StringUtils.isBlank(redirectURL)) {
                response.sendRedirect(YmlConstants.getWxComponentAuthRedirectUrl() + "/weixinauthwebfail.html");
            }
            response.sendRedirect(redirectURL);
            //统计重定向原页面的访问次数
            shortURLService.calculateVisits(code);
        } catch (Exception e) {
            LCLogger.withException("短URL重定向出错" + e);
            if (!response.isCommitted()) {
                response.sendRedirect(YmlConstants.getWxComponentAuthRedirectUrl() + "/weixinauthwebfail.html");
            }
        }
    }

    /**
     * 根据短连接编码返回原链接
     * @param code
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "findOrigin/{code}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findOrigin(@PathVariable(value = "code", required = true) String code,
                                          HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String redirectURL = shortURLService.getRedirectURL(code);
            if (StringUtils.isNotBlank(redirectURL)) {
                result.put("success", true);
                result.put("originURL", redirectURL);
                return result;
                // response.sendRedirect(YmlConstants.getWxComponentAuthRedirectUrl() + "/weixinauthwebfail.html");
            }
            result.put("success", false);
            result.put("result", "originURL is null");
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e);
            LCLogger.withException("获取短URL出错" + e);
        }
        return result;
    }

    /**
     * 更新短连接缓存
     * @param code
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "updateCache/{code}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> updateCache(@PathVariable(value = "code", required = true) String code,
                                          HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            ShortURL record = shortURLService.queryById(Long.valueOf(code));
            if (record != null) {
                shortURLService.afterUpdate(record);
                result.put("success", true);
                return result;
            }
            result.put("success", false);
            result.put("result", "无短连接信息");
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e);
            LCLogger.withException("更新短URL出错" + e);
        }
        return result;
    }
}
